package com.zw.commons.utlis.baiduai;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.zw.object.base.BaseEntity;

import java.io.File;
import java.util.*;

public class EasyDlImageClassify {
    public static String easyDlImageClassify(File file) {
        // 请求url
        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/graduationserver";
//        String imgUrl = "C:\\Users\\啊修\\Desktop\\健康码行程码图像分类\\1dea6c2e-d8b7-45a9-afc8-644c3a894483.jpg";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", Base64Util.encode(FileUtil.readFileByBytes(file)));
            map.put("top_num", "5");

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = AuthService.getAuth();
            String result = HttpUtil.post(url, accessToken, "application/json", param);
            JSONObject object = JSON.parseObject(result);
            JSONArray results = object.getJSONArray("results");
            Object name = results.getJSONObject(0).get("name");
            if("[default]".equals(name)){
                name = "识别失败";
            }
            return name.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
